package com.open.launcher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.open.launcher.R;
import com.open.launcher.bean.WebSocketGetBean;
import com.open.launcher.service.WebSocketService;
import com.open.launcher.utils.Consts;
import com.open.library.joor.Reflect;
import com.orhanobut.logger.Logger;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 强制插播
 */
public class FullPlayerActivity extends BaseActivity {

    @BindView(R.id.player_webview)
    WebView playerWebview;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_player);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        // 强制插播测试
//        Boolean b = Reflect.on("com.android.internal.policy.impl.PhoneWindowManager").field("isFullScreen").get();
//        Logger.d("插播:" + b);
//        Reflect.on("com.android.internal.policy.impl.PhoneWindowManager").set("isFullScreen", true);
//        b = Reflect.on("com.android.internal.policy.impl.PhoneWindowManager").field("isFullScreen").get();
//        Logger.d("插播:" + b);
        //
        initX5WebView();
        initBundleArgs(getIntent());
    }

    private void initX5WebView() {
        // 设置
        WebSettings webSettings = playerWebview.getSettings();
        // 设置与Js交互的权限
        webSettings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initBundleArgs(intent);
    }

    /**
     * 获取传入的播放地址.
     */
    private void initBundleArgs(Intent intent) {
        String playUrl = intent.getStringExtra("play_url");
        Logger.d("playUrl:" + playUrl);
        if (!TextUtils.isEmpty(playUrl)) {
            playerWebview.loadUrl(playUrl);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTextLoopUpdate(WebSocketGetBean webSocketGetBean) {
        // 退出强制插播
        if (WebSocketService.QUIT_FULL_LOOP == webSocketGetBean.getWay()) {
            finish();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return true;
    }

    @Override
    public void onBackPressed() {
    }

}
